<!--
 * @description: 信息 自动算法调用
 * @author: cuicui
 * @Date: 2023-11-23 11:55:06
 * @LastEditTime: 2023-11-23 14:20:17
 * @LastEditors: cuicui
-->
<template>
  <business-layout title='自动算法调用'>
    <template slot='query'>
      <a-row style='height: 40px;'>
        <a-col :span='22'>
          <a-form :form='form' layout='inline' @submit='handleQueryData'>
            <a-form-item>
              <a-input placeholder='请输入任务名称' v-decorator="['triggerName']" />
            </a-form-item>
            <a-form-item>
              <a-button type='primary' html-type='submit'>
                <a-icon type='search' />
                查询
              </a-button>
              <a-button style='margin-left: 10px' html-type='reset' @click='handleResetData'>
                重置
              </a-button>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
    </template>

    <template slot='btns'>
      <div>
        <a-button type='primary' icon='plus' @click='handleAdd'>新建</a-button>
      </div>
    </template>

    <s-table
      ref='table'
      size='default'
      rowKey='jobName'
      :columns='columns'
      :data='loadData'
      showPagination='auto'
    >
      <span slot='serial' slot-scope='text, record, index'>
        {{ index + 1 }}
      </span>
      <span slot='triggerState' slot-scope='text'>
        <a-tag :color='StateListColor[text]'>
        {{ StateList[text] }}
        </a-tag>
      </span>
      <span slot='description' slot-scope='text'>
        <ellipsis :length='4' tooltip>{{ text }}</ellipsis>
      </span>

      <span slot='action' slot-scope='text, record'>
        <template>
          <a @click='handleViewLog(record)'>日志</a>
          <a-divider type='vertical' />
          <a @click='handleEdit(record)' :disabled='["EXECUTING", "ACQUIRED"].includes(record.triggerState)'>编辑</a>
          <a-divider type='vertical' />
          <a class='del-link' @click='handleRemove(record)'
             :disabled='["EXECUTING", "ACQUIRED"].includes(record.triggerState)'>删除</a>
        </template>
      </span>
    </s-table>

    <create-auto-task
      :moduleId='moduleId'
      ref='createModal'
      :visible='visible'
      :loading='confirmLoading'
      :model='mdl'
      @cancel='handleCancel'
      @ok='handleOk'
    />

    <task-log
      :agorigthmTaskId='agorigthmTaskId'
      ref='task-log'
      :visible='logVisable'
      @cancel='logVisable = false' />
  </business-layout>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { findTriggersByPage, addTriggers, updateTriggers, deleteTiggers } from '@/api/quartz'
import CreateAutoTask from '@/business-components/create-auto-task'
import TaskLog from '@/business-components/task-log'

const moduleId = '04'
const columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '任务名称',
    dataIndex: 'jobName'
  },
  {
    title: '任务说明',
    dataIndex: 'description',
    scopedSlots: { customRender: 'description' }
  },
  {
    title: '上次执行时间',
    dataIndex: 'prevFireTime'
  },
  {
    title: '下次执行时间',
    dataIndex: 'nextFireTime'
  },
  {
    title: '状态',
    dataIndex: 'triggerState',
    scopedSlots: { customRender: 'triggerState' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateAutoTask,
    TaskLog
  },
  data() {
    this.moduleId = moduleId
    this.columns = columns
    return {
      form: this.$form.createForm(this),
      activeKey: '1',
      // create model
      visible: false,
      logVisable: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      menuId: '',
      agorigthmTaskId: '',
      // 查询参数
      queryParam: {},
      StateList: {
        'EXECUTING': '执行中',
        'ACQUIRED': '执行中',
        'WAITING': '待执行'
      },
      StateListColor: {
        'EXECUTING': 'green',
        'ACQUIRED': 'green',
        'WAITING': 'orange'
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return findTriggersByPage({ ...requestParameters, triggerGroup: this.menuId }).then(res => {
          return res
        })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  filters: {},
  created() {
    this.menuId = this.$route.fullPath
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    handleViewLog(record) {
      const { jobData } = record
      this.agorigthmTaskId = jobData.agorigthmTaskId
      this.logVisable = true
    },
    handleQueryData(e) {
      e.preventDefault()
      const form = this.form
      const that = this
      const queryObj = {}
      form.validateFields((error, values) => {
        Object.keys(values).forEach(key => {
          if (values[key]) {
            queryObj[key] = values[key]
          }
        })
        this.queryParam = queryObj
        that.$refs.table.refresh()
      })
    },
    handleResetData() {
      this.queryParam = {}
      this.form.resetFields()
      this.$refs.table.refresh()
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = {
        ...record,
        taskName: record.triggerName,
        id: 1,//手动模拟ID以区分编辑与更新
        agorigthmTaskId: record.jobData ? record.jobData.agorigthmTaskId : '',
        taskDesc: record.description
      }
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          values = {
            ...values,
            triggerGroup: this.menuId
          }
          if (values.id > 0) {
            updateTriggers(values).then(() => {
              this.visible = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('更新成功')
            }).finally(() => {
              this.confirmLoading = false
            })
          } else {
            // 新增
            addTriggers(values).then(() => {
              this.visible = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('新增成功')
            }).finally(() => {
              this.confirmLoading = false
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleRemove(record) {
      const { triggerName } = record
      const that = this
      this.$confirm({
        title: '警告',
        content: '当前操作不可逆、是否继续？',
        async onOk() {
          const result = await deleteTiggers({ triggersNames: triggerName })
          if (result) {
            that.$message.success(`删除成功`)
            that.$refs.table.refresh()
          }
        }
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    logLoadDataFun() {
      return new Promise((resolve, reject) => {
        resolve({
          endRow: 10,
          hasNextPage: false,
          hasPreviousPage: false,
          isFirstPage: false,
          isLastPage: false,
          list: [{}],
          navigateFirstPage: 0,
          navigateLastPage: 0,
          navigatePages: 0,
          navigatepageNums: null,
          nextPage: 0,
          pageNum: 1,
          pageSize: 10,
          pages: 3,
          prePage: 0,
          size: 10,
          startRow: 0,
          total: 1
        })
      })
    }
  }
}
</script>
<style lang='less' scoped>
</style>